import axios from 'axios'
// import Qs from 'qs'
import router from '@/router/index'
import store from '@/store/index'
import { Message } from 'element-ui'

const toLogin = () => {
    router.push({
        path: '/login',
        query: {
            redirect: router.currentRoute.fullPath
        }
    })
}

const api = axios.create({
    baseURL: process.env.VUE_APP_API_ROOT,
    timeout: 20000,
    // responseType: 'json'
    withCredentials: true
})
api.all = axios.all
// api.spread = axios.spread

api.interceptors.request.use(
    request => {
        request.headers['authorization'] = store.state.user.token
        if (request.method == 'post') {
            if (request.data instanceof FormData) {
                if (store.getters['user/isLogin']) {
                    // 如果是 FormData 类型（上传图片）
                    request.data.append('token', store.state.user.token)
                    // console.log(request)
                }
            } else {
                // 带上 token
                if (request.data == undefined) {
                    request.data = {}
                }
                // if (store.getters['user/isLogin']) {
                //     request.data.token = store.state.user.token
                // }
                // request.data = Qs.stringify(request.data)
            }
        } else {
            // 带上 token
            // if (request.params == undefined) {
            //     request.params = {}
            // }
            request.data = true
            // request.headers['Content-Type'] = 'application/json;charset=utf-8'
            // console.log(request)
            // if (store.getters['user/isLogin']) {
            //     request.params.token = store.state.user.token
            // }
        }
        return request
    }
)

api.interceptors.response.use(
    response => {
        // console.log(response)
        if (response.data.code === 3) {
            toLogin()
        }
        if (response.data.code !== 0) {
            // 如果接口请求时发现 token 失效，则立马跳转到登录页
            // if (response.data.status == 0) {
            //     toLogin()
            // }
            Message.error(response.data.message)
            return Promise.reject(response.data)
        }
        return Promise.resolve(response.data)
    },
    error => {
        // console.log(error.response.data)
        // console.log(error.response.status)
        // console.log(error.response.headers)
        // console.log(error.response.data.message)
        if (error.response.status === 500) Message.error(error.response.data.message || '服务器内部错误')
        return Promise.reject(error)
    }
)

export default api
